<?php

namespace App\Http\Controllers;

use App\Utils\Date;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct(Request $request)
    {
        $this->checkSite($request);
        $this->addVisitLog($request);
    }

    public function checkSite(Request $request)
    {
        $host = $request->getHost();
        $port = $request->getPort();
        if ($port && $port != 80 && $port != 443) $host = "{$host}:{$port}";

        $hostFromDb = DB::table('site')->where([
            'is_del' => 0
        ])->where('host', 'like', "%,{$host},%")->first();
        // 后台管理系统不受此限制
        if (stripos($request->url(), 'admin') !== false) {
            if ($hostFromDb && $hostFromDb->id > 0) {
                $request->siteId = $hostFromDb->id;
            }
        } else {
            if (!$hostFromDb) {
                die('该站点不存在，请在管理后台配置');
            }
            if ($hostFromDb && $hostFromDb->id > 0) {
                $request->siteId = $hostFromDb->id;
            }
        }
    }

    public function addVisitLog(Request $request)
    {
        $data = [
            'ip' => $request->ip(),
            'path' => $request->path(),
            'url' => $request->url(),
            'full_url' => $request->fullUrl(),
            'site' => $request->siteId,
            'route' => $request->route()->getName(),
            'params' => json_encode($request->query()),
            'create_time' => Date::now()
        ];
        DB::table('visitlog')->insert($data);
    }
}
